﻿<%@ WebHandler Language="C#" Class="QueryHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web.SessionState;
using Model;
using Service;
using Common;
using Cache.Redis;
using Model.User;
using Service.Table;

public class QueryHandler : IHttpHandler, IRequiresSessionState
{
    private HttpContext context;
    public void ProcessRequest(HttpContext context)
    {
        this.context = context;
        context.Response.ContentType = "text/plain";

        string methodName = string.Empty;

        //返回实体
        Dictionary<string, object> result = new Dictionary<string, object>();
        List<object> retObj = new List<object>();
        result.Add("r", 0);
        result.Add("m", "");
        result.Add("d", retObj);

        string uid = "";    //账号id

        //接收传参
        string k = context.Request["k"];    //秘钥
        var d = context.Request["d"];   //数据
        try
        {

            //验证参数
            if (string.IsNullOrEmpty(d))
            {
                result["m"] = "未检测到数据包";
                context.Response.Write(MiniJSON.Json.Serialize(result));
                return;
            }

            ////todo k 签名秘钥 需要做比较
            //if (string.IsNullOrEmpty(k) || k == "")
            //{
            //    result["m"] = "签名错误";
            //    context.Response.Write(MiniJSON.Json.Serialize(result));
            //    return;
            //}

            //解析d值
            Dictionary<string, object> objDic = (Dictionary<string, object>)MiniJSON.Json.Deserialize(d);
            //验证数据包参数
            Model.Public.RequestParam param;
            string message;
            int vp = VerifyParam(objDic, out param, out message);
            if (vp != 1)    //验证失败
            {
                result["m"] = message;
                context.Response.Write(MiniJSON.Json.Serialize(result));
                return;
            }

            uid = objDic.ContainsKey("u") ? objDic["u"].ToString() : "";

            if (param != null && param.d != null && param.d.Any())
            {
                TableService.GetTableObjectList<TableCommonProperty>(); //入口处统一获取公共属性配置
                //根据command_id，分别调用对应业务逻辑进行处理
                foreach (var item in param.d)
                {
                    var pItem = (Dictionary<string, object>)item;

                    Dictionary<string, object> data = new Dictionary<string, object>(); //返回实体中，最外层的d
                    Dictionary<string, object> list = new Dictionary<string, object>(); //返回实体中，里面数据中的d
                    data.Add("o", pItem.ContainsKey("o") ? pItem["o"].ToString() : ""); //对应序列id
                    //data.Add("r", 0);
                    data.Add("d", list);

                    int c = pItem.ContainsKey("c") ? Convert.ToInt32(pItem["c"]) : 0;
                    ServiceConfig config = new ServiceConfig();
                    IQueryInterface service = config.GetQueryService(c);    //根据command_id，调用对应的业务逻辑模块进行处理
                    if (service != null)
                    {
                        Dictionary<string, object> pItem_d = (Dictionary<string, object>)pItem["p"];    //真正的参数字段部分
                        methodName = service.GetType().Name;
                        //接口中处理返回实体字段 r d
                        service.GetData(uid, pItem_d, ref list);
                    }

                    retObj.Add(data);
                }

                result["r"] = 1;  //至此，数据处理成功
            }
        }
        catch (Exception err)
        {
            LogHelper.Error(err.Message, err);  //记录异常日志
            result["r"] = 999;
            result["m"] = err.ToString();
        }

        context.Response.Write(MiniJSON.Json.Serialize(result));
    }

    /// <summary>
    /// 验证参数
    /// </summary>
    /// <param name="objDic">参数</param>
    /// <param name="param">返回</param>
    /// <param name="message">提示信息</param>
    /// <returns></returns>
    public int VerifyParam(Dictionary<string, object> objDic, out Model.Public.RequestParam param, out string message)
    {
        int result = 0;
        param = null;
        message = "";
        if (objDic == null || !objDic.Any())
        {
            message = "未检测到数据包";
        }
        else
        {
            param = new Model.Public.RequestParam();

            ////uid，账号或者角色id
            //if (!objDic.ContainsKey("u"))
            //{
            //    message = "未检测到参数u";
            //    return result;
            //}
            param.u = !objDic.ContainsKey("u") ? "" : objDic["u"].ToString();
            //请求数量
            if (objDic.ContainsKey("t"))
            {
                param.t = Convert.ToInt32(objDic["t"]);
            }
            if (param.u != "")  //当有UID的时候，才会去校验token
            {
                //s token
                if (!objDic.ContainsKey("s"))
                {
                    message = "未检测到参数s";
                    return result;
                }
                param.s = !objDic.ContainsKey("s") ? "" : objDic["s"].ToString();

                //验证token是否正确
                string value = RedisHelper.instance.GetHash(LoginLogData.login_token, param.u);
                //如果token不一致或者token已经过期一天，则需要重新登录
                if (param.s != value || DateTime.Now.CompareTo(CheckInfo.ConvertUTCTimeStampToDateTime(Convert.ToInt64(value)).AddDays(1)) >= 0)
                {
                    message = "token过期";
                    return result;
                }
            }
            //d 参数数据
            if (!objDic.ContainsKey("d"))
            {
                message = "未检测到参数d";
                return result;
            }
            param.d = !objDic.ContainsKey("d") ? new List<object>() : (List<object>)objDic["d"];
            result = 1;
        }
        return result;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}